import type { App } from "vue";
import axios from "axios";
import { useConfigStore } from "@/stores/config";
import { platformConfigsStorage } from "./storage";

/** 获取项目动态全局配置 */
export const setPlatformConfigs = async (app: App): Promise<PlatformConfigs> => {
    let config = platformConfigsStorage.value ?? {};
    // 如果localStorage中没有配置，则从public目录下获取
    if (!Object.entries(config).length) {
        const { data }: { data: PlatformConfigs } = await axios({
            method: "get",
            url: `/platform-config.json`,
        }).catch(() => {
            throw new Error("请在public文件夹下添加platform-config.json配置文件");
        });
        config = data;
    }
    // 自动注入系统配置
    if (app && typeof config === "object") {
        /*
            Note[pinia] 将一个 state 补丁应用于 pinia 的当前状态
            $patch: https://pinia.vuejs.org/zh/api/interfaces/pinia._StoreWithState.html#patch
        */
        useConfigStore().$patch({ config });
        // 设置localStorage
        platformConfigsStorage.value = Object.assign(platformConfigsStorage.value ?? {}, config);
    }
    return config;
};
